#! /usr/bin/python

"""
Removes the email addresses in the file given as the first argument
from the files given in the subsequent arguments. Files must be in
cvs (comma-separated values) format.

Writes the stripped lists to files with 'NEW_' prepended to the original
filename. Writes the addresses that got stripped (and the sum of how many
were) to files with 'RMV_' prepended to the filename.
"""

import re, sys, string

if len(sys.argv) < 3 :
	print "Error - wrong number of command line arguments"
	sys.exit(0)

print ""
respLines = open(sys.argv[1], 'r').readlines()

emails = set()
rmdCount = 0

# Iterate through files to remove addresses from.
for name in sys.argv[2:] :
	print "Removing emails in", sys.argv[1], "from", name, "\n"
	listLines = open(name, 'r').readlines()
	newLines = []
	rmdLines = []

	# Iterate through lines in the list containing emails to remove.
	for respLine in respLines :
		vals = re.split(',', respLine)

		# If there's an email in this line, it's the second token.
		if vals[1].find('@') != -1 : # Found one!
			email = string.lower(vals[1]) # Get the address.
			emails.add(email)
			#print "Removing", email, "from", name, ", if present"

			# Iterate through the list to be culled.
			for i in range(0, len(listLines)) :

				# If we don't find it, let it stay in the new list for now.
				if string.lower(listLines[i]).find(email) == -1 :
					newLines.append(listLines[i])
				# If we do find it, add it to the removed list.
				else :
					rmdLines.append(listLines[i])
					rmdCount = rmdCount + 1

			# Make sure to save the updated list for the next iteration and reset
			# the placeholder!
			listLines = newLines
			newLines = []	

	newList = open("NEW_" + name, 'w')
	newList.writelines(listLines)
	rmdList = open("RMV_" + name, 'w')
	rmdList.writelines(rmdLines)
	rmdList.write("Total files removed from " + name + ": " + str(len(rmdLines)))

	newList.close()

	#print ""

print len(emails), "unique emails found in", sys.argv[1]
print rmdCount, "total emails removed from the given files"
